<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title>凭证管理</title>
	<link rel="stylesheet" href="../../component/pear/css/pear.css" />
</head>

<body class="pear-container">
	<div class="layui-card">
		<div class="layui-card-body">
			<form class="layui-form" action="">
				<div class="layui-form-item">
					<div class="layui-form-item layui-inline">
						<label class="layui-form-label">名称</label>
						<div class="layui-input-inline">
							<input type="text" name="name" id="name" placeholder="请输入名称" class="layui-input">
						</div>
					</div>
					<div class="layui-form-item layui-inline">
						<label class="layui-form-label">凭证
						</label>
						<div class="layui-input-inline">
							<input type="text" name="access_token" id="access_token" placeholder="请输入Token" class="layui-input">
						</div>
					</div>
					<div class="layui-form-item layui-inline">
						<label class="layui-form-label">状态</label>
						<div class="layui-input-inline">
							<select name="is_active" id="is_active" lay-search>
								<option value="">请下拉选择</option>
								<option value="0">禁用</option>
								<option value="1">启用</option>
							</select>
						</div>
					</div>
					<br>
					<div class="layui-form-item layui-inline">
						<button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="base-query">
							<i class="layui-icon layui-icon-search"></i>
							查询
						</button>
						<button type="reset" class="pear-btn pear-btn-md">
							<i class="layui-icon layui-icon-refresh"></i>
							重置
						</button>
					</div>
				</div>
			</form>
		</div>
	</div>
	<div class="layui-card">
		<div class="layui-card-body">
			<table id="base-table" lay-filter="base-table"></table>
		</div>
	</div>

	<script type="text/html" id="base-toolbar">
		<button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add">
			<i class="layui-icon layui-icon-add-1"></i>
			新增
		</button>
	</script>

	<script type="text/html" id="base-bar">
		<button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</button>
		<button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="remove"><i class="layui-icon layui-icon-delete"></i>删除</button>
	</script>
	<script type="text/html" id="base-is-active">
		{{#if (d.is_active == 0) { }}
		<i class="layui-icon layui-icon-face-cry" style="font-size: 30px; color: #ff1e1e;"><span>禁用</span></i>  
		{{# }else if(d.is_active == 1){ }}
		<i class="layui-icon layui-icon-face-smile" style="font-size: 30px; color: #1E9FFF;"><span>启用</span></i> 
		{{# } }}
	</script>
	<script type="text/html" id="token-column">
		<div style="display: flex; align-items: center; justify-content: space-between;">
			<span class="token-preview" style="flex: 1; overflow: hidden; text-overflow: ellipsis; font-family: monospace;">
				{{ d.access_token ? '••••••••••' : '未生成' }}
			</span>
			<div style="display: flex; gap: 5px; margin-left: 10px;">
				<button class="layui-btn layui-btn-xs layui-btn-normal view-token" 
						title="查看Access Token" 
						style="padding: 0 5px;"
						data-token="{{ d.access_token || '' }}">
					<i class="layui-icon layui-icon-search"></i>
				</button>
				<button class="layui-btn layui-btn-xs layui-btn-primary copy-token" 
						title="复制Access Token" 
						style="padding: 0 5px;" 
						{{# if(!d.access_token) { }}disabled lay-disabled{{# } }}>
					<i class="layui-icon layui-icon-file"></i>
				</button>
			</div>
		</div>
	</script>
	<script src="../../component/com/api.js"></script>
	<script src="../../component/com/auth.js"></script>
	<script src="../../component/layui/layui.js"></script>
	<script src="../../component/pear/pear.js"></script>
	<script>
		layui.use(['table', 'form', 'jquery', 'common'], function () {
			let table = layui.table;
			let form = layui.form;
			let $ = layui.jquery;
			let common = layui.common;
			let layer = layui.layer;
			let MODULE_PATH = "config/";
			let API_BASE_URL = apiConfig.baseUrl;
			let token = window.localStorage.getItem("token") || window.sessionStorage.getItem("token")

			let cols = [
				[{
					type: 'checkbox'
				},
				{
					title: '序号',
					field: 'id',
					align: 'left',
					width: 80,
				},
				{
					title: '名称',
					field: 'name',
					align: 'left',
					width: 100,
				},
				{
					title: '状态',
					field: 'is_active',
					align: 'left',
					width: 100,
					templet: '#base-is-active'
				},
				{
					title: 'Access Token',
					field: 'access_token',
					align: 'center',
					width: 200,
					templet: '#token-column'
				},
				{
					title: '允许IP',
					field: 'allowed_ips',
					align: 'center',
					width: 150,
				},
				{
					title: '用途说明',
					field: 'description',
					align: 'center',
					width: 150,
				},
				{
					title: '过期时间',
					field: 'expires_time',
					align: 'center',
					width: 160,
				},
				{
					title: '创建时间',
					field: 'create_time',
					align: 'center',
					width: 160,
				},
				{
					title: '更新时间',
					field: 'update_time',
					align: 'center',
					width: 160,
					hide: true
				},
				{
					title: '操作',
					toolbar: '#base-bar',
					align: 'center',
					width: 230,
					fixed: "right"
				}]
			]

			table.render({
				elem: '#base-table',
				url: `${API_BASE_URL}/common/token/`,
				page: true,
				request: {
					pageName: 'page',
					limitName: 'limit'
				},
				limits: [10, 20, 30, 40, 50, 100],
				limit: 10,
				cols: cols,
				skin: 'line',
				toolbar: '#base-toolbar',
				headers: {
					"Authorization": token
				},
				parseData: function (res) {
					return {
						"code": res.success ? 0 : 1,
						"msg": res.message || "操作成功",
						"count": res.data.count,
						"data": res.data.results,
						"curr": res.data.current_page
					};
				},
				done: function(res, curr, count){
					bindTokenEvents();
				},
				defaultToolbar: [{
					title: '刷新',
					layEvent: 'refresh',
					icon: 'layui-icon-refresh',
				}, 'filter', 'print', 'exports']
			});

			// 绑定表格工具栏事件
			table.on('tool(base-table)', function (obj) {
				switch (obj.event) {
					case "edit":
						window.edit(obj)
						break;
					case "remove":
						window.remove(obj)
						break;
				}
			});

			table.on('toolbar(base-table)', function (obj) {
				switch (obj.event) {
					case "add":
						window.add(obj)
						break;
					case "refresh":
						window.refresh(obj)
						break;
					case "batchRemove":
						window.batchRemove(obj)
						break;
				}
			});

			// 绑定查询表单事件
			form.on('submit(base-query)', function (data) {
				table.reload('base-table', {
					where: data.field,
					page: { curr: 1 }
				})
				return false;
			});

			// Token相关事件绑定（查看/复制）
			function bindTokenEvents() {
				// 查看Token功能
				$('.view-token').off('click').on('click', function() {
					const tokenValue = $(this).data('token') || '';
					if (!tokenValue) {
						layer.msg('Token未生成或为空', { icon: 2, time: 1000 });
						return;
					}
					
					layer.open({
						type: 1,
						title: '查看Token',
						area: ['500px', '300px'],
						content: `
							<div style="padding: 20px;">
								<div style="margin-bottom: 15px; color: #666;">Token内容：</div>
								<textarea id="token-textarea" readonly 
									style="width: 100%; height: 120px; padding: 10px; 
									border: 1px solid #ddd; border-radius: 4px; 
									background: #f8f8f8; font-family: monospace; 
									resize: none;">${tokenValue}</textarea>
								<div style="margin-top: 15px; text-align: center;">
									<button class="layui-btn layui-btn-sm layui-btn-primary" 
											id="copy-token-btn">复制Token</button>
								</div>
							</div>
						`,
						success: function(layero, index){
							$('#copy-token-btn').on('click', function() {
								copyToClipboard(tokenValue, () => {
									layer.msg('Token已复制', { icon: 1, time: 1000 });
								});
							});
						}
					});
				});
				
				// 复制Token功能（核心修复：使用access_token字段）
				$('.copy-token').off('click').on('click', function() {
					const $row = $(this).closest('tr');
					const index = $row.data('index');
					const data = table.cache['base-table'][index];
					
					if (!data.access_token) {
						layer.msg('Token未生成或为空', { icon: 2, time: 1000 });
						return;
					}
					
					copyToClipboard(data.access_token, () => {
						layer.msg('Token已复制', { icon: 1, time: 1000 });
					});
				});
			}

			// 复制到剪贴板工具函数
			function copyToClipboard(text, successCallback) {
				if (navigator.clipboard && window.isSecureContext) {
					navigator.clipboard.writeText(text).then(successCallback).catch(err => {
						console.error('Clipboard API failed:', err);
						fallbackCopy(text, successCallback);
					});
				} else {
					fallbackCopy(text, successCallback);
				}
			}

			// 复制降级方案（兼容旧浏览器）
			function fallbackCopy(text, successCallback) {
				const textarea = document.createElement('textarea');
				textarea.value = text;
				textarea.style.position = 'fixed';
				textarea.style.left = '-999px';
				document.body.appendChild(textarea);
				textarea.select();
				document.execCommand('copy');
				document.body.removeChild(textarea);
				successCallback();
			}

			// 窗口操作函数
			window.add = function () {
				layer.open({
					type: 2,
					title: '新增凭证',
					shade: 0.1,
					area: ['600px', '450px'],
					content: MODULE_PATH + 'token-add.html'
				});
			}

			window.edit = function (obj) {
				layer.open({
					type: 2,
					title: `编辑凭证: [${obj.data.name}]`,
					shade: 0.1,
					area: ['600px', '500px'],
					content: MODULE_PATH + `token-edit.html?id=${obj.data.id}`
				});
			}

			window.remove = function (obj) {
				layer.confirm(`确定要删除Token：[ ${obj.data.name} ] ？`, {
					icon: 3,
					title: '提示: 凭证删除'
				}, function (index) {
					layer.close(index);
					let loading = layer.load();
					$.ajax({
						url: `${API_BASE_URL}/common/token/${obj.data.id}/`,
						dataType: 'json',
						type: 'delete',
						headers: {
							"Authorization": token
						},
						success: function (result) {
							layer.close(loading);
							if (result.success) {
								layer.msg(result.message, {
									icon: 1,
									time: 1000
								}, function () {
									obj.del();
								});
							} else {
								layer.msg(result.message, {
									icon: 2,
									time: 1000
								});
							}
						},
						error: function() {
							layer.close(loading);
							layer.msg('网络错误，请稍后重试', { icon: 2 });
						}
					})
				});
			}

			window.refresh = function () {
				table.reload('base-table');
			}

			window.batchRemove = function () {
				layer.msg('批量删除功能待实现', { icon: 3 });
			}
		})
	</script>
</body>
</html>